<?php

/**
 * @package Nina
 * @author Andrew Rose <rose.andrew@gmail.com>, John Main <john@thedaddy.org>
 */
class Nina_Db_Driver_Mysql implements Nina_Db_Driver
{
	private $reg;
	private $dbcon;
	
	public function init(Nina_Registry $reg) {
		$this->reg = $reg;

		if($reg->exists('username,password,hostname')) {
			if($this->connect()) {
				if($this->reg->exists('database') && !$this->database())
					throw new Nina_Exception_Db('Unable to select database ' . $this->reg->get('database'));
				else
					return true;
			}
			else
				throw new Nina_Exception_Db('Unable to establise database connection');
		}
		else
			throw new Nina_Exception_Db('Unable to initilize driver. Missing parameters.');
	}

	public function connect() {
		return ($this->dbcon = mysql_connect($this->reg->get('hostname'), $this->reg->get('username'), $this->reg->get('password')));
	}

	public function database() {
		return mysql_select_db($this->reg->get('database'), $this->dbcon);
	}
	
	public function prepare($sql) {
		$stmt = new Nina_Db_Driver_Statement_Mysql();
		$stmt->setDb($this);
		$stmt->setSql($sql);
		return $stmt;
	}

	public function begin() {
		return $this->query("BEGIN;");
	}

	public function commit() {
		return $this->query("COMMIT;");
	}

	public function rollback() {
		return $this->query("ROLLBACK;");
	}

	/**
	 * Get the database fields
	 * @param string $table Table name
	 * @return array
	 */
	public function getFields($table) {
		$rs = $this->query('SHOW COLUMNS FROM ' . $table);
		if ($rs->count()) {
			$fields = array();

			while ($row = $rs->row()) {
				$fields[] = $row['Field'];
			}

			return $fields;
		}
		else
			return false;
	}

	/**
	 * Get the database tables
	 * @return array
	 */
	public function getTables() {
		$rs = $this->query('SHOW TABLES');
		if ($rs->count()) {
			$tables = array();

			while ($row = $rs->row()) {
				$tables[] = reset($row);
			}

			return $tables;
		}
		else
			return false;
	}

	public function query($query) {
		mysql_select_db($this->reg->get('database'));

		$result = new Nina_Db_Driver_Result_Mysql();
		$result->setDbcon($this->dbcon);
		if($rs = mysql_query($query, $this->dbcon)) {
			$result->setResult($rs);
			return $result;
		}
		else
			throw new Nina_Exception_Db_Driver(mysql_error());
	}
	
	public function insertId() {
		return mysql_insert_id($this->dbcon);
	}
	
	public function escape($data) {
		return mysql_real_escape_string($data, $this->dbcon);
	}
	
	public function lastError() {
		return mysql_error($this->dbcon);
	}

	public function close() {
		return mysql_close($this->dbcon);
	}

	public function ping() {
		return mysql_ping($this->dbcon);
	}
}
